from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from datetime import datetime

from app.api import deps
from app.schemas import workarea_transaction as schemas
from app.database.models.erp import WorkArea, WorkAreaTransaction
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[schemas.WorkAreaTransaction])
def list_transactions(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取交易记录列表"""
    if current_user.role == "admin":
        # 管理员可以查看所有交易
        transactions = db.query(WorkAreaTransaction).offset(skip).limit(limit).all()
    else:
        # 普通用户只能查看自己工作区的交易
        transactions = db.query(WorkAreaTransaction).filter(
            WorkAreaTransaction.WorkAreaId == current_user.workarea_id
        ).offset(skip).limit(limit).all()
    return transactions

@router.post("/", response_model=schemas.WorkAreaTransaction)
def create_transaction(
    *,
    db: Session = Depends(deps.get_db),
    transaction_in: schemas.WorkAreaTransactionCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新交易记录"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 验证工作区是否存在
    workarea = db.query(WorkArea).filter(WorkArea.ID == current_user.workarea_id).first()
    if not workarea:
        raise HTTPException(status_code=404, detail="WorkArea not found")
    
    # 如果是提现，检查余额是否足够
    if transaction_in.TransactionType == "withdraw" and workarea.Balance < transaction_in.Amount:
        raise HTTPException(
            status_code=400,
            detail="Insufficient balance for withdrawal"
        )
    
    transaction = WorkAreaTransaction(
        **transaction_in.dict(),
        WorkAreaId=current_user.workarea_id,
        CreateTime=datetime.now(),
        PaymentStatus="pending"
    )
    
    db.add(transaction)
    db.commit()
    db.refresh(transaction)
    return transaction

@router.get("/{transaction_id}", response_model=schemas.WorkAreaTransaction)
def get_transaction(
    transaction_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定交易记录"""
    transaction = db.query(WorkAreaTransaction).filter(
        WorkAreaTransaction.ID == transaction_id
    ).first()
    
    if not transaction:
        raise HTTPException(status_code=404, detail="Transaction not found")
    
    # 权限检查
    if (current_user.role != "admin" and 
        transaction.WorkAreaId != current_user.workarea_id):
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    return transaction

@router.put("/{transaction_id}/complete", response_model=schemas.WorkAreaTransaction)
def complete_transaction(
    *,
    db: Session = Depends(deps.get_db),
    transaction_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """完成交易"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    transaction = db.query(WorkAreaTransaction).filter(
        WorkAreaTransaction.ID == transaction_id
    ).first()
    
    if not transaction:
        raise HTTPException(status_code=404, detail="Transaction not found")
    
    if transaction.PaymentStatus != "pending":
        raise HTTPException(status_code=400, detail="Transaction already processed")
    
    # 更新工作区余额
    workarea = db.query(WorkArea).filter(WorkArea.ID == transaction.WorkAreaId).first()
    if transaction.TransactionType == "deposit":
        workarea.Balance += transaction.Amount
    else:  # withdraw
        if workarea.Balance < transaction.Amount:
            raise HTTPException(status_code=400, detail="Insufficient balance")
        workarea.Balance -= transaction.Amount
    
    # 更新交易状态
    transaction.PaymentStatus = "completed"
    transaction.PaymentTime = datetime.now()
    
    db.add(workarea)
    db.add(transaction)
    db.commit()
    db.refresh(transaction)
    return transaction

@router.put("/{transaction_id}/cancel", response_model=schemas.WorkAreaTransaction)
def cancel_transaction(
    *,
    db: Session = Depends(deps.get_db),
    transaction_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """取消交易"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    transaction = db.query(WorkAreaTransaction).filter(
        WorkAreaTransaction.ID == transaction_id
    ).first()
    
    if not transaction:
        raise HTTPException(status_code=404, detail="Transaction not found")
    
    if transaction.PaymentStatus != "pending":
        raise HTTPException(status_code=400, detail="Transaction already processed")
    
    transaction.PaymentStatus = "cancelled"
    transaction.PaymentTime = datetime.now()
    
    db.add(transaction)
    db.commit()
    db.refresh(transaction)
    return transaction 